package org.levi.demo;

import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.cache.PathChildrenCache;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.CreateMode;

public class ServerList {

    public static void main(String[] args) throws Exception {

        RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
        CuratorFramework zkClient = CuratorFrameworkFactory.newClient("127.0.0.1:2181", retryPolicy);
        zkClient.start();

        String path = "/servers";
        String[] hosts = {"127.0.0.1:8081", "127.0.0.1:8082"};

        PathChildrenCache pathChildrenCache = new PathChildrenCache(zkClient, path, true);
        pathChildrenCache.start(PathChildrenCache.StartMode.BUILD_INITIAL_CACHE);
        pathChildrenCache.getListenable().addListener((curatorFramework, pathChildrenCacheEvent) -> {
            System.out.println("=======================>子节点变更=====>>>>" + pathChildrenCacheEvent.getData().getPath());
        });
        String childNodePath = path+"/server-host";
        for (int i = 0; i < hosts.length; i++) {
            zkClient.create().creatingParentsIfNeeded().withMode(CreateMode.EPHEMERAL_SEQUENTIAL).forPath(childNodePath,hosts[i].getBytes());
        }
        Thread.sleep(3000);
        //删除子节点
        zkClient.delete().forPath(path+"/"+zkClient.getChildren().forPath(path).get(0));
        Thread.sleep(10000);
    }
}
